import Request from '@/js_sdk/luch-request/luch-request/index.js'
import Config from '@/config/config.js'
import {
	encryptBase64,
	encryptWithAes,
	generateAesKey,
	decryptWithAes,
	decryptBase64,
} from "@/utils/crypto";
import {
	encrypt,
	decrypt
} from "@/utils/jsencrypt.js";
const http = new Request({
	baseURL: Config.base_url, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'content-type': 'application/json; charset=UTF-8;',
		'Access-Control-Allow-Origin': '*',
	},
})
//请求拦截器
http.interceptors.request.use((config) => {
	const token = uni.getStorageSync('token');
	if (token) {
		config.header["Clientid"] = "428a8310cd461950ue699df5d894f886"
		config.header["Authorization"] = 'Bearer ' + token
	} else {
		config.header["Clientid"] = "428a8310cd461950ue699df5d894f886"
	}
	// 是否需要加密
	const isEncrypt = (config.header || {}).isEncrypt;
	// 当开启参数加密
	if (isEncrypt && config.method === "post") {
		// 生成一个 AES 密钥
		const aesKey = generateAesKey();
		config.header['encrypt-key'] = encrypt(encryptBase64(aesKey));
		config.data = typeof config.data === "object" ?
			encryptWithAes(JSON.stringify(config.data), aesKey) :
			encryptWithAes(config.data, aesKey);
	} else {
		if (config.method === 'POST') {
			config.data = JSON.stringify(config.data);
		}
	}
	return config
}, error => {
	return Promise.resolve(error)
})

// 响应拦截器
http.interceptors.response.use((response) => {
	// 加密后的 AES 秘钥
	const keyStr = response.header['encrypt-key'];
	// 加密
	if (keyStr != null && keyStr != "") {
		const data = response.data;
		// 请求体 AES 解密
		const base64Str = decrypt(keyStr);
		// base64 解码 得到请求头的 AES 秘钥
		const aesKey = decryptBase64(base64Str.toString());
		// aesKey 解码 data
		const decryptData = decryptWithAes(data, aesKey);
		// 将结果 (得到的是 JSON 字符串) 转为 JSON
		response.data = JSON.parse(decryptData);
	}
	//判断登录过期跳回登录页
	if (response.data.code == 401) {
		uni.clearStorageSync();
		uni.reLaunch({
			url: "/pages/login/index"
		})
	} else if (response.data.code == 200) {
		return response.data
	} else if (response.data.code == 500) {
		uni.showToast({
			icon: 'none',
			title: response.data.msg,
			duration: 3000
		});
		return response.data.msg
	} else {
		return response.data.msg
	}
	return response.data
}, (error) => {
	//未登录时清空缓存跳转
	if (error.statusCode == 401) {
		// uni.clearStorageSync();
		uni.reLaunch({
			url: "/pages/index/index"
		})
	}
	return Promise.resolve(error)
})
export default http;